package com.zhsj.OkeHomeConsumption.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.hjq.base.BaseDialog;
import com.hjq.dialog.WaitDialog;
import com.hjq.widget.ClearEditText;
import com.hjq.widget.CountdownView;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.event.LoginOutEvent;
import com.zhsj.OkeHomeConsumption.event.LoginUserpanterEvent;
import com.zhsj.OkeHomeConsumption.helper.InputTextHelper;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeOutHandler;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.CodeUtils;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.internal.ListenerClass;

import static com.zhsj.OkeHomeConsumption.common.Constants.SHARED_PERFERENCE_USERINFO;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 登录界面
 */
public final class LoginActivity extends MyActivity {
    @BindView(R.id.login_ck)
    CheckBox loginCk;

    private BaseDialog pDialogUtils = null;
    //手机号码输入框
    @BindView(R.id.et_register_phone)
    EditText etRegisterPhone;
    //验证码发送
    @BindView(R.id.cv_register_countdown)
    CountdownView cvRegisterCountdown;
    ///验证码输入框
    @BindView(R.id.et_login_password)
    ClearEditText etLoginPassword;
    //登录按钮
    @BindView(R.id.btn_login_commit)
    Button btnLoginCommit;


    @BindView(R.id.login_text)
    TextView login_text;
    @BindView(R.id.login_text2)
    TextView login_text2;

    private SharedPreferanceUtils mSharePreferanceUtils = null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_login_title;
    }

    @Override
    protected void initView() {
        String str = "我已阅读并接受<font color='#1976d2'>《用户使用协议》</font>";
        String str2="和<font color='#1976d2'>《隐私政策》</font>";
        login_text.setText(str);
        login_text2.setText(str2);

        login_text.setText(Html.fromHtml(str));
        login_text2.setText(Html.fromHtml(str2));
        new InputTextHelper.Builder(this)
                .setMain(btnLoginCommit)
                .addView(etLoginPassword)
                .addView(etRegisterPhone)
                .build();
        pDialogUtils = new BaseDialog(this);
    }

    @Override
    protected void initData() {
        mSharePreferanceUtils = new SharedPreferanceUtils(getActivity());
        etLoginPassword.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                setButtonBackground();
            }
        });
    }

    @Override
    public void onRightClick(View v) {

    }

    @Override
    public boolean isSupportSwipeBack() {
        // 不使用侧滑功能
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.et_register_phone, R.id.cv_register_countdown, R.id.et_login_password, R.id.btn_login_commit, R.id.login_ck, R.id.login_text,R.id.login_text2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_register_phone:
                break;
            case R.id.cv_register_countdown:
                // 发送验证码
                String strPhoneNum = etRegisterPhone.getText().toString().trim();
                if (TextUtils.isEmpty(strPhoneNum)) {
                    toast("请填写手机号");
                    cvRegisterCountdown.resetState();
                    return;
                }
                if (etRegisterPhone.getText().toString().length() != 11) {
                    toast("请输入正确的手机号码");
                    cvRegisterCountdown.resetState();
                    return;
                }
                SendCodevolleyPost(strPhoneNum);
                break;
            case R.id.et_login_password:
                break;
            case R.id.btn_login_commit:
                String strPhoneNumlog = etRegisterPhone.getText().toString().trim();
                String et_login_password = etLoginPassword.getText().toString().trim();
                if (TextUtils.isEmpty(et_login_password)) {
                    toast("请填写验证码");
                    cvRegisterCountdown.resetState();
                    return;
                }
                if (loginCk.isChecked() == true) {
                    LogOnPost(strPhoneNumlog, et_login_password);
                } else if (loginCk.isChecked() == false) {
                    toast("请勾选阅读协议之后登录");
                }
                break;
            case R.id.login_text:
                Intent intent = new Intent(getActivity(), WebActivity.class).putExtra("url",
                        OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/contract/2.html");
                startActivity(intent);
                break;
            case R.id.login_text2:
                Intent intent2 = new Intent(getActivity(), WebActivity.class).putExtra("url",
                        OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/contract/1.html");
                startActivity(intent2);
                break;
        }
    }

//          @param
//    @return void    返回类型
//      @throws
//    @Title setButtonBackground
//    @Description TODO 设置登录按钮的背景颜色

    private void setButtonBackground() {
        String username = etRegisterPhone.getText().toString().trim();
        String userpwd = cvRegisterCountdown.getText().toString().trim();
        if (username.length() != 0 && userpwd.length() != 0) {
            btnLoginCommit.setClickable(true);
        } else {
            btnLoginCommit.setClickable(false);
        }
    }

    /**
     * @Title: SendCodevolleyPost @Description: TODO 获取验证码异步线程 @param @param
     * strPhoneNum 输入的手机号 @return void 返回类型 @throws
     */
    public void SendCodevolleyPost(String strPhoneNum) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        String phoneString = CodeUtils.encryptAES(strPhoneNum, CodeUtils.password);
        mSendCodeHashMap.put("mobile", phoneString);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        paramMaps.put("mobile", phoneString);
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = new WaitDialog.Builder(this)
                .setMessage("加载中...") // 消息文本可以不用填写
                .show();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_SMSCODE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                TimeOutHandler.pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        toast("验证码已发送");
                    } else {
                        cvRegisterCountdown.resetState();
                        TimeOutHandler.pDialogUtils.dismiss();
                        toast("验证码发送失败");
                    }
                } catch (Exception ex) {
                    TimeOutHandler.pDialogUtils.dismiss();
                }

            }

            @Override
            public void onFailure(Throwable e) {
                super.onFailure(e);
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
            }
        });

    }

    public void LogOnPost(String strPhoneNum, String code) {
        // TODO Auto-generated method stub
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        final HashMap<String, String> mLogOnHashMap = new HashMap<String, String>();
        // mParamHashMap.put("token", Constants.TOKEN);
        mLogOnHashMap.put("v", Constants.APPVERSION);
        mLogOnHashMap.put("t", Constants.TIME);
        mLogOnHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mLogOnHashMap.put("client", Constants.CLIENT);
        mLogOnHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mLogOnHashMap.put("platform", Constants.PLAFORM);
        String phoneString = CodeUtils.encryptAES(strPhoneNum, CodeUtils.password);
        mLogOnHashMap.put("loginonAPI", phoneString);
        mLogOnHashMap.put("code", code);
        paramMaps.put("loginonAPI", phoneString);
        paramMaps.put("code", code);
        // 网络计时器及线程
        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = new WaitDialog.Builder(this)
                .setMessage("加载中...") // 消息文本可以不用填写
                .show();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mLogOnHashMap);
        HttpClient.post(OkeHomeConsumptionApi.ELVDOU_LOGINON, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                TimeOutHandler.pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        JSONObject dataLoginobj = jsonOBJ.optJSONObject("data");
                        FormalUserInfo userInfo = JsonUtils.object(dataLoginobj.toString(), FormalUserInfo.class);
                        mSharePreferanceUtils.setToken(userInfo.getToken());
                        String str = mSharePreferanceUtils.getToken();

                        EventBus.getDefault().post(userInfo);
                        EventBus.getDefault().post(new LoginOutEvent(0));
//                       //userInfo.getLifeUserDTO().getLifeType()
                        if(userInfo.getLifeUserDTO().getDepositStatusType()==4||userInfo.getLifeUserDTO().getDepositStatusType()==3){
                            EventBus.getDefault().post(new LoginUserpanterEvent(0));
                        }else{
                            switch (userInfo.getLifeUserDTO().getLifeType()) {
                                case 0:
                                    //会员
                                    mSharePreferanceUtils.setlifeType(0);
                                    EventBus.getDefault().post(new LoginUserpanterEvent(0));
                                    break;
                                case 1:
                                    //商家
                                    mSharePreferanceUtils.setlifeType(1);
                                    EventBus.getDefault().post(new LoginUserpanterEvent(1));
                                    break;
                                case 2:
                                    //城市合伙人
                                    mSharePreferanceUtils.setlifeType(2);
                                    EventBus.getDefault().post(new LoginUserpanterEvent(2));
                                    break;
                            }
                        }
                        finish();
                    } else {
                        if (!message.equals("null")) {
                            toast(message);
                            TimeOutHandler.pDialogUtils.dismiss();
                        }
                    }
                } catch (JSONException ex) {
                    TimeOutHandler.pDialogUtils.dismiss();
                }

            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
            }
        });
    }


}